﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using SocialExplorer.FastDBF;
using System.Collections.Specialized;
using Barbar.MapReport.DataSource.Resources;

namespace Barbar.MapReport.DataSource.Esri {
  public class EsriRegionProvider : RegionProvider {
    private string m_DbfPath;
    private string m_IdColumnName;
    private string m_NameColumnName;

    public override void Initialize(string name, NameValueCollection config) {
      base.Initialize(name, config);
      if (config == null)
        throw new ArgumentNullException("config");

      m_DbfPath = config["dbfPath"];
      if (String.IsNullOrEmpty(m_DbfPath))
        throw new DataSourceException("dbfPath is not specified.");

      m_IdColumnName = config["idColumnName"];
      if (String.IsNullOrEmpty(m_IdColumnName))
        throw new DataSourceException("idColumnName is not specified.");

      m_NameColumnName = config["nameColumnName"];
      if (String.IsNullOrEmpty(m_NameColumnName))
        throw new DataSourceException("nameColumnName is not specified.");
    }

    internal static IEnumerable<EsriRawRegion> GetRegions(string path, string idColumnName, string nameColumnName) {
      DbfFile file = new DbfFile();
      file.Open(path, FileMode.Open);
      DbfColumn idColumn = file.Header[idColumnName];
      if (idColumn == null)
        throw new DataSourceException("Id column not found.");

      DbfColumn nameColumn = null;
      if (!String.IsNullOrEmpty(nameColumnName))
        nameColumn = file.Header[nameColumnName];

      DbfRecord record = file.ReadNext();
      int index = 0;
      while (record != null) {
        string id = record[record.FindColumn(idColumn.Name)];
        string name = null;
        if (nameColumn != null)
          name = record[record.FindColumn(nameColumn.Name)];
        yield return new EsriRawRegion(id, name, index);
        index++;
        record = file.ReadNext();
      }
    }
    
    public override IEnumerable<IRawRegion> Regions {
      get {
        foreach(EsriRawRegion region in GetRegions(m_DbfPath, m_IdColumnName, m_NameColumnName))
          yield return region;
      }
    }
  }
}
